import { createLogger } from "@/utils/logger"
import { useAuth } from "./useAuth"
import { tokenStore } from "@/utils/cached"
import { useEffect, useRef } from "react"
import ApiFetchers from "@/apis/api_fetchers"

const logger = createLogger("useTokenCheck")

const CHECK_INTERVAL = 1000 * 60 * 4 // 4分钟轮询一次

export function useTokenCheck() {
    const { logout } = useAuth()
    const token = tokenStore.get()

    const checkRef = useRef<NodeJS.Timeout | undefined>(undefined)
    const isLoggingOut = useRef(false)

    // 判断 token 是否有效
    const isTokenValid = !!token && !!token.accessToken

    const checkAndRefreshToken = async () => {
        if (!isTokenValid || isLoggingOut.current) return
        try {
            const res = await ApiFetchers.refRefreshToken()
            if (!res || res.data !== "ok" || res.status !== true) {
                logger.debug("token invalid, logout")
                isLoggingOut.current = true
                await logout()
                return
            }
        } catch (error) {
            logger.debug("token check error, logout", error)
            isLoggingOut.current = true
            await logout()
            return
        }
    }

    useEffect(() => {
        isLoggingOut.current = false
        if (!isTokenValid) {
            if (checkRef.current) {
                clearInterval(checkRef.current)
                checkRef.current = undefined
            }
            return
        }
        checkAndRefreshToken()
        checkRef.current = setInterval(checkAndRefreshToken, CHECK_INTERVAL)
        const onVisible = () => {
            if (document.visibilityState === "visible") checkAndRefreshToken()
        }
        document.addEventListener("visibilitychange", onVisible)
        return () => {
            if (checkRef.current) {
                clearInterval(checkRef.current)
                checkRef.current = undefined
            }
            document.removeEventListener("visibilitychange", onVisible)
        }
        // eslint-disable-next-line
    }, [isTokenValid])
}
